/**
 * 视频资源预加载
 * 用法
 * import preload from 'libs/preloadImages';
 * preload(srcs, cb);
 * srcs 待加载的视频路径的集合
 * cb 加载结束回调，不管是否全部加载成功
 */

const loadedSrcs = {};

export default function (srcs, cb) {
  if (!srcs.length) return cb && cb([]);
  let progress = 0;
  let successSrcs = [];
  let onEach = () => ++progress == srcs.length && cb && cb(successSrcs);
  srcs.forEach(src => {
    if (loadedSrcs[src]) {
      successSrcs.push(src);
      onEach();
    } else {
      let video = document.createElement('video');
      video.src = src;
      video.oncanplaythrough = function () {
        let src = this.getAttribute('src');
        loadedSrcs[src] = true;
        successSrcs.push(src);
        onEach();
      };
      video.onerror = function () {
        console.log(this.src + '加载失败');
        onEach();
      };
    }
  });
}